//
//  MessageController.m
//  20240823
//
//  Created by 张伟 on 2024/8/28.
//

#import "MessageController.h"
#import "MessageCell.h"

@interface MessageController ()
@property (nonatomic) bool isRequested;
@end

@implementation MessageController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (UserModel.shared.isLogin && self.isRequested == false) {
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.title = localizedStringKey(@"message");
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:localizedStringKey(@"newMessage") forState:UIControlStateNormal];
    [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(toNewMessageControllerAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    [self.tableView cellWithNib:MessageCell.class];
    [self addRefreshHeaderAndFooter];
}

-(void)loadData {
    NSDictionary * parame = @{
        @"userId":@(UserModel.shared.userId),
        @"page":@(self.page),
        @"size":@(self.pageSize)
    };
    
    MJWeakSelf
    [NetService requestMessageList:parame successHandle:^(NSArray<MessageModel *> * _Nonnull array) {
        if (weakSelf.isRequested == false) {
            weakSelf.isRequested = true;
        }
        if (weakSelf.page == 0) {
            [weakSelf.dataSource removeAllObjects];
        }
        [weakSelf.dataSource addObjectsFromArray:array];
        [weakSelf.tableView reloadData];
        [weakSelf endRefresh];
    } fail:^{
        
    }];
}

- (void)refreshAction {
    self.page = 0;
    [self loadData];
}

- (void)loadMoreAction {
    self.page ++;
    [self loadData];
}

-(void)toNewMessageControllerAction{
    MJWeakSelf
    [VCRouter toNewMessageController:^{
        [weakSelf loadData];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCell * cell = [tableView dequeueWithClass:MessageCell.class];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

@end
